package com.ff.device.controller;

import com.ff.device.domain.DeviceInfo;
import com.ff.device.result.CodeMsg;
import com.ff.device.result.Result;
import com.ff.device.service.DeviceService;
import com.ff.device.util.CmdUtils;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    @GetMapping("")
    public String toDeviceList(){
        return "device_list";
    }

    @ResponseBody
    @RequestMapping("all")
    public Result<List<DeviceInfo>> getDeviceList(){
        List<DeviceInfo> resultList=deviceService.getDeviceList();
        Result result=Result.success(resultList);
        return result;
    }


    @ResponseBody
    @RequestMapping("connect")
    public Result<Boolean> connectToDevice(@RequestParam("deviceIp") String deviceIp){
        boolean result=deviceService.addDevice(deviceIp);
        if (!result){
           return Result.error(CodeMsg.DEVICE_ADD_FAILURE);
        }
        return Result.success(result);
    }

    @ResponseBody
    @RequestMapping("disconnect")
    public Result<Boolean> disconnectToDevice(@RequestParam("deviceIp") String deviceIp){
        if (!deviceService.checkDeviceExist(deviceIp)){
            return Result.error(CodeMsg.DEVICE_NOT_FOUND);
        }
        boolean result=deviceService.delDevice(deviceIp);
        return Result.success(result);
    }

    @ResponseBody
    @RequestMapping("update")
    public Result<Boolean> updateDevice(@RequestParam("devid") String devid,@RequestParam("name") String name){
        DeviceInfo deviceInfo=deviceService.findByDeviceInfo(devid);
        deviceInfo.setName(name);
        boolean result=deviceService.updateDevice(deviceInfo);
        return Result.success(result);
    }
}
